﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using YinfangWeb.BLL;
using YinfangWeb.BLL.Enum;
using YinfangWeb.BLL.Model;
using YinfangWeb.MLog;

namespace YinfangWeb.Api.Controllers
{
    [OperateTrack]
    public class UserController : ApiController
    {
        private readonly UserBO _userBO = new UserBO();
        #region 用户 登录
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="token"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        /// src\store\modules\user.js
        [HttpPost]        
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]         
        public IHttpActionResult Login(string token,[FromBody]JObject obj)
        {
            
            dynamic model = obj;
            if (model == null) return Json(new Result(ResultCode.ParameterMissing));
            string username = model.username;
            string password = model.password;
            string identity = model.identity;

            if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(identity))
            {
                return Json(new Result(ResultCode.AccountParameterMissing));
            }

            try
            {
                var clientIp = Request.GetClientIpAddress();
                var result = _userBO.LoginByPassword(identity, username, password, clientIp);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("用户登录发生错误，错误信息：", ex);
                return Json(new Result(ResultCode.AccountLoginFail));
            }
        }
        #endregion
        #region 用户 登出
        /// <summary>
        /// 用户退出登录
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// src\store\modules\user.js
        [HttpGet]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        public IHttpActionResult Logout(string token)
        {            
            try
            {
                return Json(new Result());
            }
            catch (Exception ex)
            {
                Logger.Default.Error("用户退出登录出错！", ex);
                return Json(new Result(ResultCode.Busy,ex.Message));
            }
        }
        #endregion
        #region 账号 返回账号信息 通过Token
        /// <summary>
        /// 账号 返回账号信息 通过Token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1.
        [HttpGet]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        public IHttpActionResult GetAccountInfoByToken(string token)
        {
            try
            {
                var result = _userBO.GetAccountInfoByToken(token);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("GetAccountInfoByToken，错误信息：", ex);
                return Json(new Result(ResultCode.Busy));
            }
        }
        #endregion

        #region 角色 列表
        /// <summary>
        /// 角色 列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1.src\views\user\role\set\index.vue
        [HttpGet]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        public IHttpActionResult GetRoleListKeyInfo()
        {
            try
            {
                var result = _userBO.GetRoleListKeyInfo();
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("GetRoleListKeyInfo，错误信息：", ex);
                return Json(new Result(ResultCode.Busy));
            }
        }
        #endregion
        #region 权限 列表
        /// <summary>
        /// 权限 列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1.src\views\user\role\set\index.vue
        [HttpGet]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        public IHttpActionResult GetRightItemAll()
        {
            try
            {
                var result = _userBO.GetRightItemAll();
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("GetRightItemAll，错误信息：", ex);
                return Json(new Result(ResultCode.Busy));
            }
        }
        #endregion
        #region 权限 当前角色权限ID值
        /// <summary>
        /// 权限 当前角色权限ID值
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1.src\views\user\role\set\index.vue
        [HttpGet]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        public IHttpActionResult GetRightIDListByRole(string token, string identity, string roleid)
        {
            //dynamic model = obj;
            //string roleid = model.roleid;
            try
            {
                var result = _userBO.GetRightIDListByRole(Convert.ToInt32(roleid));
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("GetRightIDListByRole，错误信息：", ex);
                return Json(new Result(ResultCode.Busy));
            }
        }
        #endregion
        #region 权限 当前用户权限code值 通过token
        /// <summary>
        /// 权限 当前用户权限code值 通过token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1.src\store\modules\permission.js
        [HttpGet]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        public IHttpActionResult GetRightCodeListByToken(string token, string identity)
        {
            try
            {
                var result = _userBO.GetRightCodeListByToken(token);
                return Json(result);
            }
            catch (Exception ex)
            {
                Logger.Default.Error("GetRightCodeListByToken，错误信息：", ex);
                return Json(new Result(ResultCode.Busy));
            }
        }
        #endregion
        #region 权限 保存当前角色权限值
        /// <summary>
        /// 权限 保存当前角色权限值
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        /// 1.src\views\user\role\set\index.vue
        [HttpPost]
        [ValidToken]
        [ValidRole(EnumUserRole.Manager)]
        public IHttpActionResult SaveUserRight(string token, [FromBody]JObject obj)
        {
            dynamic model = obj;
            if (model == null) return Json(new Result(ResultCode.ParameterMissing));
            try
            {
                string roleid = model.GwGroupID;
                List<int> list = model.GwRightItemID.system.ToObject<List<int>>();
                var result = _userBO.SaveRight(Convert.ToInt32(roleid), list);
                return Json(new Result(ResultCode.Success));
            }
            catch (Exception ex)
            {
                Logger.Default.Error("GetRightStringByRole，错误信息：", ex);
                return Json(new Result(ResultCode.Busy));
            }
        }
        #endregion
    }

    #region HTTP请求扩展类 取IP
    /// <summary>
    /// HTTP请求扩展类
    /// </summary>
    public static class HttpRequestMessageExtensions
    {
        private const string HttpContext = "MS_HttpContext";
        private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";
        /// <summary>
        /// 取客户端地址
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string GetClientIpAddress(this HttpRequestMessage request)
        {
            if (request.Properties.ContainsKey(HttpContext))
            {
                dynamic ctx = request.Properties[HttpContext];
                if (ctx != null)
                {
                    return ctx.Request.UserHostAddress;
                }
            }

            if (request.Properties.ContainsKey(RemoteEndpointMessage))
            {
                dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
                if (remoteEndpoint != null)
                {
                    return remoteEndpoint.Address;
                }
            }

            return null;
        }
    }
    #endregion
}
